<script lang="ts" setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { GetFukaCardOption, GetFukaOption } from '@/api/modules/fukaact'
import { GetFukaUserDeta, PostSenddrawchanceData, PostSendfukaData } from '@/api/modules/fukaactUser'
import PageNumber from '@/store/modules/PageNumberCache'

// const imgDomain = 'https://img1.eprhan.cc'
const route = useRoute()
const router = useRouter()
const PageNumberCache = PageNumber()

// 查询表单
const findFrom = reactive({
  FukaActId: route.query.fukaActId as string,
  UserId: '',
  OpenId: '',
})

const dataList: any = reactive({
  list: [],
})

const OptionList = reactive({
  fukaOption: [],
})

const loading = ref(true)
const total = ref(0)
let PageSize = 20

async function GetDataList(PageIndex: number = 1, PageSize: number = 20) {
  const params = {
    PageIndex,
    PageSize,
    ...(findFrom.FukaActId && { FukaActId: findFrom.FukaActId }),
    ...(findFrom.UserId && { UserId: findFrom.UserId }),
    ...(findFrom.OpenId && { OpenId: findFrom.OpenId }),
  }
  await GetFukaUserDeta(params).then(async (dataRes: any) => {
    if (dataRes.succeeded) {
      dataList.list = dataRes.data.items
      total.value = dataRes.data.total
      loading.value = false
    }
    else {
      ElMessage.error(`查询失败。${dataRes.errors}`)
      loading.value = false
    }
  })
    .catch(() => {
      loading.value = false
    })
  loading.value = false
}

// 查询
function Inquire() {
  GetDataList(1, PageSize)
}

function SkipPage(name: any, UserId?: string) {
  router.push({
    name: `${name}`,
    query: {
      fukaActId: findFrom.FukaActId,
      ...(UserId && { UserId }),
    },
  })
}

// 补卡和发送抽奖机会
// 决定单个对话框中的内容，1为发送抽奖机会，2为补卡
let dialogType = 0
const dialogVisible = ref(false)
// 对话框提交的数据
const senddrawchanceSetData = ref({
  fukaActId: 0,
  orderNo: '',
})
const sendfukaSetData = ref({
  fukaActId: 0,
  fukaUserId: 0,
  fukaCardId: 0,
  sendType: 0,
})
// 福卡卡片ID选项列表
const CardIdOption = ref<any>([])
function OpenDialog(type: number, row: any) {
  dialogType = type
  dialogVisible.value = true
  if (type === 1) {
    senddrawchanceSetData.value.fukaActId = row.fukaActId
    senddrawchanceSetData.value.orderNo = ''
  }
  else if (type === 2) {
    sendfukaSetData.value.fukaActId = row.fukaActId
    sendfukaSetData.value.fukaUserId = row.id
    // console.log(sendfukaSetData.value)
    sendfukaSetData.value.fukaCardId = 0
    sendfukaSetData.value.sendType = 0
    GetFukaCardOption(sendfukaSetData.value.fukaActId).then((res: any) => {
      if (res.succeeded) {
        CardIdOption.value = res.data
      }
      else {
        ElMessage.error(`获取福卡列表失败。${res.errors}`)
      }
    })
  }
}
// 提交数据
function SetFromData() {
  if (dialogType === 1) {
    // console.log(senddrawchanceSetData.value)

    PostSenddrawchanceData(senddrawchanceSetData.value).then((res: any) => {
      if (res.succeeded) {
        ElMessage.success('发送抽奖机会成功')
        dialogVisible.value = false
        GetDataList()
      }
      else {
        ElMessage.error(`发送抽奖机会失败。${res.errors}`)
      }
    })
  }
  else if (dialogType === 2) {
    // console.log(sendfukaSetData.value)

    PostSendfukaData(sendfukaSetData.value).then((res: any) => {
      if (res.succeeded) {
        ElMessage.success('补卡成功')
        dialogVisible.value = false
        GetDataList()
      }
      else {
        ElMessage.error(`补卡失败。${res.errors}`)
      }
    })
  }
  dialogVisible.value = false
}

// 翻页
function handleSizeChange(val: number) {
  GetDataList(1, val)
  PageSize = val
}
function handleCurrentChange(val: number) {
  GetDataList(val, PageSize)
  PageNumberCache.SetFukaUserPage(val)
}

const nowPageNum = computed(() => {
  return PageNumberCache.GetFukaUserPage()
})

onMounted(async () => {
  // 获取福卡活动
  const fukaData: any = await GetFukaOption()
  if (fukaData.succeeded) {
    OptionList.fukaOption = fukaData.data
    if (route.query.fukaActId === undefined) {
      findFrom.FukaActId = fukaData.data[0].fukaActId
    }

    nextTick(() => {
      OptionList.fukaOption = fukaData.data
    })
  }
  if (findFrom.FukaActId) {
    GetDataList(PageNumberCache.GetFukaUserPage())
  }
  else {
    ElMessage.error('请先选择福卡活动')
    loading.value = false
  }
})
</script>

<template>
  <div>
    <PageMain>
      <SearchBar :show-toggle="false">
        <div class="header">
          <el-form label-positio="right" label-width="auto">
            <div class="from">
              <el-form-item label="福卡活动">
                <el-select v-model="findFrom.FukaActId" filterable placeholder="请选择福卡活动">
                  <el-option v-for="item in (OptionList.fukaOption as any[])" :key="item.fukaActId" :label="(item.fukaActId as any)" :value="item.fukaActId" />
                </el-select>
              </el-form-item>
              <el-form-item label="用户ID">
                <el-input v-model="findFrom.UserId" placeholder="请输入用户ID" @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="微信用户ID">
                <el-input v-model="findFrom.OpenId" placeholder="请输入微信用户ID" @keyup.enter="Inquire" />
              </el-form-item>
            </div>
          </el-form>
          <div class="text-right">
            <el-button @click="Inquire">
              查询
            </el-button>
          </div>
        </div>
      </SearchBar>
      <ElDivider border-style="dashed" />
      <!-- <div class="mb-5 text-right">

      </div> -->
      <el-table v-loading="loading" :data="dataList.list" stripe style="width: 100%;" border>
        <el-table-column align="center" prop="id" label="福卡用户ID" width="120" />
        <el-table-column align="center" prop="fukaActId" label="福卡活动ID" width="100" />
        <el-table-column align="center" prop="subscriberInfo.userId" label="用户ID" width="100" />
        <!-- <el-table-column align="center" prop="subscriberInfo.scOpenId" label="OpenID" width="280" /> -->
        <el-table-column align="center" prop="subscriberInfo" label="用户信息" width="200">
          <template #default="scope">
            <div v-if="!scope.row.subscriberInfo">
              未授权
            </div>
            <el-tooltip
              v-else
              class="box-item"
              effect="dark"
              :content="scope.row.subscriberInfo?.scOpenId"
              placement="top"
            >
              <div class="user-name">
                <el-avatar :size="40" style="margin-right: 10px;" :src="scope.row.subscriberInfo?.userAvatar" />
                <div>
                  <p style="margin: 0;">
                    {{ scope.row.subscriberInfo?.userNickName }}
                  </p>
                  <span>
                    {{ scope.row.subscriberInfo?.userPhone }}
                  </span>
                </div>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column align="center" width="140" prop="fuKa1" label="福卡1剩余数量" />
        <el-table-column align="center" width="140" prop="fuKa2" label="福卡2剩余数量" />
        <el-table-column align="center" width="140" prop="fuKa3" label="福卡3剩余数量" />
        <el-table-column align="center" width="140" prop="fuKa4" label="福卡4剩余数量" />
        <el-table-column align="center" width="140" prop="fuKa5" label="福卡5剩余数量" />
        <el-table-column align="center" width="140" prop="drawCount" label="福卡剩余抽奖次数" />
        <el-table-column align="center" width="240" prop="addTime" label="添加时间" />
        <el-table-column align="center" width="240" prop="updateTime" label="修改时间" />
        <el-table-column align="center" label="操作" fixed="right" min-width="360">
          <template #default="scope">
            <div style="line-height: 42px;">
              <el-button type="info" @click="SkipPage('fukaUserDetail', scope.row.subscriberInfo.userId)">
                福卡明细
              </el-button>
              <el-button type="info" @click="SkipPage('fukaUserPrize', scope.row.subscriberInfo.userId)">
                奖品列表
              </el-button>
              <el-button type="info" @click="SkipPage('fukaUserZhuli', scope.row.subscriberInfo.userId)">
                助力记录
              </el-button>
              <el-button type="info" @click="SkipPage('fukaUserZhuliTicket', scope.row.subscriberInfo.userId)">
                助力发券记录
              </el-button>
              <el-button type="success" @click="OpenDialog(1, scope.row)">
                发送抽卡机会
              </el-button>
              <el-button type="success" @click="OpenDialog(2, scope.row)">
                补卡
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div style="height: 10px;" />
      <el-pagination
        :default-page-size="20"
        :page-sizes="[5, 10, 20, 50, 100]"
        layout="total, sizes, ->, prev, pager, next, jumper"
        :total="total"
        :default-current-page="nowPageNum"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </PageMain>
    <el-dialog
      v-model="dialogVisible"
      title=""
      width="500"
      destroy-on-close
    >
      <div v-if="dialogType === 1">
        <el-form :model="senddrawchanceSetData">
          <el-form-item label="订单号">
            <el-input v-model="senddrawchanceSetData.orderNo" />
          </el-form-item>
        </el-form>
      </div>
      <div v-else-if="dialogType === 2">
        <el-form :model="sendfukaSetData">
          <el-form-item label="福卡" label-width="100px">
            <el-radio-group v-model="sendfukaSetData.fukaCardId">
              <el-radio v-for="item in CardIdOption" :key="item.fukaCardId" :value="item.fukaCardId">
                {{ item.fukaName }}
              </el-radio>
            </el-radio-group>
            <!-- <el-select v-model="" placeholder="请选择福卡">
              <el-option v-for="item in CardIdOption" :key="item.fukaCardId" :label="item.fukaName" :value="item.fukaCardId" />
            </el-select> -->
          </el-form-item>
          <el-form-item label="补卡类型" label-width="100px">
            <el-radio-group v-model="sendfukaSetData.sendType">
              <el-radio :value="0">
                明细和数量
              </el-radio>
              <el-radio :value="1">
                仅明细
              </el-radio>
              <el-radio :value="2">
                仅数量
              </el-radio>
            </el-radio-group>
            <!-- <el-select v-model="sendfukaSetData.sendType" placeholder="请选择补卡类型">
              <el-option label="明细和数量" :value="0" />
              <el-option label="仅明细" :value="1" />
              <el-option label="仅数量" :value="2" />
            </el-select> -->
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="SetFromData">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.header {
  display: grid;
  grid-template-columns: 6fr 1fr;

  .from {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    grid-gap: 20px;

    .el-form-item {
      margin-bottom: 0;
    }
  }
}

.scrollbar-flex-content {
  display: flex;
  max-width: 300px;

  .scrollbar-flex-img {
    display: flex;
    flex-shrink: 0;
    align-items: center;
    justify-content: center;
    width: auto;
    height: 60px;
    margin-right: 10px;
  }
}

.user-name {
  display: flex;
  align-items: center;
  justify-content: left;

  div {
    text-align: left;
  }
}
</style>
